package com.yt.base.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.*;
import org.dom4j.io.*;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

public class XmlUtil {

	private static final Log logger = LogFactory.getLog(XmlUtil.class);

	public XmlUtil() {
	}

	public static String docToString(Document document) {
		String s = "";
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			OutputFormat format = new OutputFormat("  ", true, "UTF-8");
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(document);
			s = out.toString("UTF-8");
		} catch (Exception ex) {
			logger.error((new StringBuilder("docToString error:")).append(ex.getMessage()).toString());
		}
		return s;
	}

	public static Document stringToDocument(String s) {
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(s);
		} catch (Exception ex) {
			logger.error((new StringBuilder("stringToDocument error:")).append(ex.getMessage()).toString());
		}
		return doc;
	}

	public static boolean docToXmlFile(Document document, String filename) {
		boolean flag = true;
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileOutputStream(new File(filename)), format);
			writer.write(document);
			writer.close();
		} catch (Exception ex) {
			flag = false;
			logger.error((new StringBuilder("docToXmlFile error:")).append(ex.getMessage()).toString());
		}
		return flag;
	}

	public static boolean stringToXmlFile(String str, String filename) {
		boolean flag = true;
		try {
			Document doc = DocumentHelper.parseText(str);
			flag = docToXmlFile(doc, filename);
		} catch (Exception ex) {
			flag = false;
			logger.error((new StringBuilder("stringToXmlFile error:")).append(ex.getMessage()).toString());
		}
		return flag;
	}

	public static Document load(String filename) {
		return load(new File(filename));
	}

	public static Document load(File file) {
		Document document = null;
		try {
			SAXReader saxReader = new SAXReader();
			saxReader.setEncoding("UTF-8");
			document = saxReader.read(file);
		} catch (Exception ex) {
			logger.error((new StringBuilder("load XML File error:")).append(ex.getMessage()).toString());
		}
		return document;
	}

	public static Document load(String filename, String encode) {
		Document document = null;
		try {
			SAXReader saxReader = new SAXReader();
			saxReader.setEncoding("encode");
			document = saxReader.read(new File(filename));
		} catch (Exception ex) {
			logger.error((new StringBuilder("load XML File error:")).append(ex.getMessage()).toString());
		}
		return document;
	}

	public static Document load(InputStream is) {
		Document document = null;
		try {
			SAXReader saxReader = new SAXReader();
			saxReader.setEncoding("UTF-8");
			document = saxReader.read(is);
		} catch (Exception ex) {
			logger.error((new StringBuilder("load XML File error:")).append(ex.getMessage()).toString());
		}
		return document;
	}

	public static Document load(InputStream is, String encode) {
		Document document = null;
		try {
			SAXReader saxReader = new SAXReader();
			saxReader.setEncoding(encode);
			document = saxReader.read(is);
		} catch (Exception ex) {
			logger.error((new StringBuilder("load XML File error:")).append(ex.getMessage()).toString());
		}
		return document;
	}

	public static Document styleDocument(Document document, String stylesheet) throws Exception {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer(new StreamSource(stylesheet));
		DocumentSource source = new DocumentSource(document);
		DocumentResult result = new DocumentResult();
		transformer.transform(source, result);
		Document transformedDoc = result.getDocument();
		return transformedDoc;
	}

	public static void main(String args[]) {
		String filePath = "L:/devtools/workspace/eoffice/web/js/menu.xml";
		String style = "L:/devtools/workspace/eoffice/web/js/menu-public.xsl";
		Document doc = load(filePath);
		try {
			Document another = styleDocument(doc, style);
			System.out.println((new StringBuilder("xml:")).append(another.asXML()).toString());
			Document publicDoc = another;
			Element rootEl = publicDoc.getRootElement();
			List idNodes = rootEl.selectNodes("/Menus//*");
			System.out.println((new StringBuilder("size:")).append(idNodes.size()).toString());
			for (int i = 0; i < idNodes.size(); i++) {
				Element el = (Element) idNodes.get(i);
				Attribute attr = el.attribute("id");
				if (attr != null)
					System.out.println((new StringBuilder("attr:")).append(attr.getValue()).toString());
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
